#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cv.h>
#include <highgui.h>
#include "sr.h"
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <assert.h>

using namespace std;
using namespace cv;
//void findChePai(IplImage src, int width, int height, int thread_low, int thread__high)
//{
//	int w = src->width;
//	int h = src->height;
//	int n = src->nChannels;
//	int step = src->widthStep;
//
//	thread(src, 100, 150);
//}
//
//int 
//
//
//void thread(IplImage src, int low, int high)
//{
//	assert(src->nChannels == 1);
//#ifdef DEBUG
//	cvNamedWindow("win_1");
//	cvShowImage("win_1", src);
//#endif
//	unsigned char *data =(unsigned char *) src->imageData;
//	for (int i = 0; i < src->height; ++ i) {
//		for (int j = 0; j < src->width; ++ j) {
//			if (data[i * step + j] < high  && data[i * step + j] > low) {
//				data[i * step + j] = 255;
//			}
//			else data[i * step + j] = 0;
//		}
//	}
//#ifdef DEBUG
//	cvShowImage("win_1", src);
//	cvDestroyWindow("win_1");
//#endif
//	return;
//}


void roi()
{
	char *name_src = (char *) malloc (sizeof(char) * 256);
	char *name_dst = (char *) malloc (sizeof(char) * 256);
	name_src = (char *) "res/temp/capture00.bmp";
	name_dst = (char *) "res/temp/chepai.png";
	Mat src = imread(name_src);
	Mat dst = imread(name_dst);
	Mat result;
	int result_cols = src.cols - dst.cols + 1;
	int result_rows = src.rows - dst.rows + 1;
	result.create(result_cols, result_rows, CV_32FC1);

	matchTemplate(src, dst, result, CV_TM_SQDIFF_NORMED);
	double minVal;
	double maxVal;
	Point minLoc;
	Point maxLoc;
	minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc, Mat());
	rectangle(result, minLoc, Point(minLoc.x + dst.cols, minLoc.y + dst.rows), Scalar::all(0), 2, 8, 0);

	cvNamedWindow("win_1");
	imshow("win_1", result);
	cvWaitKey(0);

	return;
}

static Mat img; Mat templ; Mat result;
char* image_window = "Source Image";
char* result_window = "Result window";
char *name = (char *) malloc (sizeof(char) * 256);

int match_method;
int image_select;
int max_Trackbar = 5;
int max_image = 23;

/// 函数声明
void MatchingMethod( int, void* );
void selectImage(int ,void*);

/** @主函数 */
int _roi( int argc, char** argv )
{
  /// 载入原图像和模板块
  img = imread( argv[1], 1 );
  templ = imread( argv[2], 1 );

  /// 创建窗口
  namedWindow( image_window, CV_WINDOW_AUTOSIZE );
  namedWindow( result_window, CV_WINDOW_AUTOSIZE );

  /// 创建滑动条
  char* trackbar_label = "Method: \n 0: SQDIFF \n 1: SQDIFF NORMED \n 2: TM CCORR \n 3: TM CCORR NORMED \n 4: TM COEFF \n 5: TM COEFF NORMED";
  createTrackbar( trackbar_label, image_window, &match_method, max_Trackbar, MatchingMethod );
  char* trackbar_label_image = "Select a image";
  createTrackbar( trackbar_label_image, image_window, &image_select, max_image, selectImage);

  MatchingMethod( 0, 0 );

  waitKey(0);
  return 0;
}

/**
 * @函数 selectImage
 * @简单的选择图片滑动回调函数
 */
void selectImage(int, void*)
{
	memset(name, 0, sizeof(char) * 256);
	strcpy(name, (char *)"res/temp/capture");
	char *index_char = (char *) malloc (sizeof(char) * 56);
	memset(index_char, 0, sizeof(char) * 56);
	sprintf(index_char, "%02d.bmp", image_select);
	strcat(name, index_char);
	printf("%s\n", name);
	img = imread(name, 1);
	imshow( image_window, img );
	MatchingMethod(0, 0);
	return;
}

/**
 * @函数 MatchingMethod
 * @简单的滑动条回调函数
 */
Point matchLoc;
void MatchingMethod( int, void* )
{
  /// 将被显示的原图像
  Mat img_display;
  img.copyTo( img_display );

  /// 创建输出结果的矩阵
  int result_cols =  img.cols - templ.cols + 1;
  int result_rows = img.rows - templ.rows + 1;

  result.create( result_cols, result_rows, CV_32FC1 );

  /// 进行匹配和标准化
  matchTemplate( img, templ, result, match_method );
  normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );

  /// 通过函数 minMaxLoc 定位最匹配的位置
  double minVal; double maxVal; Point minLoc; Point maxLoc;

  minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );

  /// 对于方法 SQDIFF 和 SQDIFF_NORMED, 越小的数值代表更高的匹配结果. 而对于其他方法, 数值越大匹配越好
  if( match_method  == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED )
    { matchLoc = minLoc; }
  else
    { matchLoc = maxLoc; }

  /// 最终结果
  rectangle( img_display, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );
  rectangle( result, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );

  imshow( image_window, img_display );
  imshow( result_window, result );

  return;
}

void outFindResult(char **imgSet, int cnt)
{
	templ = imread( "res/temp/chepai.png", 1 );
	for (int i = 0; i < cnt; ++ i) {
		char *saveNmae = (char *) malloc (sizeof(char) * 256);
		strcpy(saveNmae, imgSet[i]);
		sprintf(saveNmae, "%d", i);
		img = imread(imgSet[i], 1);
		printf("%s\n", imgSet[i]);
		MatchingMethod(0, 0);
		IplImage img_temp = img;
		IplImage *img_interest = &img_temp;

		IplImage *sub_img = cvCreateImageHeader(
				cvSize(templ.cols, templ.rows),
				IPL_DEPTH_8U,
				3
				);
		sub_img->widthStep = img_interest->widthStep;
		sub_img->origin = img_interest->origin;
		sub_img->imageData = img_interest->imageData + 
					matchLoc.y * img_interest->widthStep +
					matchLoc.x * img_interest->nChannels;

		strcat(saveNmae, ".png");
		char *saveName = (char *) malloc (sizeof(char) * 256);
		strcpy(saveName, (char *) "res/result/");
		strcat(saveName, saveNmae);
		printf("%s\n", saveName);
		cvSaveImage(saveName, sub_img);
	}
}
